<script setup lang="ts">
import { FieldValues, PlusColumn, PlusForm } from "plus-pro-components";
import { ref } from "vue";
import { useSelect } from "@/utils/useSelect";
import { createUser } from "@/api/user";
import { message } from "@/utils/message";
import { useRouter } from "vue-router";
const { usersStatusList } = useSelect();
const router = useRouter();
defineOptions({
  name: "userAdd"
});

const submitLoading = ref(false);
const state = ref<FieldValues>({
  username: "",
  password: "",
  oldPassword: "",
  status: null,
  birthday: null,
  realName: "",
  phone: "",
  level: 0
});

const rules = {
  username: {
    required: true,
    message: "请输入用户名"
  },
  password: {
    required: true,
    message: "请输入密码"
  },
  oldPassword: [
    {
      required: true,
      message: "请再次输入密码"
    },
    {
      validator: (rule, value, callback) => {
        if (value !== state.value.password) {
          callback(new Error("两次密码输入不一致"));
        } else {
          callback();
        }
      }
    }
  ]
};

const columns: PlusColumn[] = [
  {
    label: "用户名",
    prop: "username",
    fieldProps: {
      placeholder: "请输入用户名"
    }
  },
  {
    label: "密码",
    prop: "password",
    fieldProps: {
      placeholder: "请输入密码",
      type: "password"
    }
  },
  {
    label: "确认密码",
    prop: "oldPassword",
    fieldProps: {
      placeholder: "请再次输入密码",
      type: "password"
    }
  },
  {
    label: "真实姓名",
    prop: "realName",
    fieldProps: {
      placeholder: "请选择真实姓名"
    }
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: usersStatusList,
    fieldProps: {
      placeholder: "请选择"
    },
    hideInForm: true
  },
  {
    label: "生日",
    prop: "birthday",
    valueType: "date-picker",
    fieldProps: {
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "手机号",
    prop: "phone",
    fieldProps: {
      placeholder: "请输入手机号"
    }
  },
  {
    label: "等级",
    prop: "level",
    valueType: "input-number",
    fieldProps: {
      placeholder: "请选择",
      min: 0
    }
  }
];

function submit(values: FieldValues) {
  submitLoading.value = true;
  createUser(state.value)
    .then(res => {
      message(res.message, { type: "success" });
      router.push({
        name: "usersList"
      });
    })
    .finally(() => {
      submitLoading.value = false;
    });
}
</script>

<template>
  <el-card header="新增用户" shadow="never">
    <template #default>
      <PlusForm
        v-model="state"
        class="w-full md:w-[300px]"
        label-position="top"
        :columns="columns"
        :rules="rules"
        :submit-loading="submitLoading"
        @submit="submit"
      />
    </template>
  </el-card>
</template>
